package com.llkj.qingnianguoxue.course;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.jm.chat.pickerimage.utils.StringUtil;
import com.llkj.qingnianguoxue.R;
import com.llkj.qingnianguoxue.base.BaseActivity;
import com.llkj.qingnianguoxue.base.ConstantUserInfo;
import com.llkj.qingnianguoxue.base.MyApplication;
import com.llkj.qingnianguoxue.bean.CoursePayBean;
import com.llkj.qingnianguoxue.bean.ExchangeBean;
import com.llkj.qingnianguoxue.bean.RxCoursePayBean;
import com.llkj.qingnianguoxue.http.HttpMethod;
import com.llkj.qingnianguoxue.util.GsonUtil;
import com.llkj.qingnianguoxue.util.ImageLoadingUtil;
import com.llkj.qingnianguoxue.util.PayMethodViewUtil;
import com.llkj.qingnianguoxue.util.RxBus;
import com.sevenheaven.iosswitch.ShSwitchView;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.PushNotificationBuilder;

public class CoursePayActivity extends BaseActivity implements PayMethodViewUtil.PaySuccessListener {
    public static final String CATEGORYTYPE = "CategoryType";
    public static final int REQUEST_PAY_CODE = 9907;
    @BindView(R.id.ivCover)
    ImageView ivCover;//封面
    @BindView(R.id.tvCourseTitle)
    TextView tvTitle;//标题
    @BindView(R.id.tvCourseTime)
    TextView tvCourseTime;//课程时间
    @BindView(R.id.tvCoursePrice)
    TextView tvCoursePrice;//单价
    @BindView(R.id.tv_total_money)
    TextView tvTotalMoney;//总价
    @BindView(R.id.tv_deduction_money)
    TextView tvDeduction;//抵扣
    @BindView(R.id.tv_pay_money)
    TextView tvActualMoney;//实际支付
    @BindView(R.id.sw_open)
    ShSwitchView swOpenBtn;//抵扣开关
    @BindView(R.id.btnPayCourse)
    TextView btnPayMoney;//支付按钮

    private float mPrepareMoney,mActualMoney;//预支付金额,实际支付金额
    private PayMethodViewUtil payMethodViewUtil;
    private int categoryType;//默认0课程，1活动
    private String mCourseId;
    private String mPicUrl;
    private String mDetailTitle;
    private String mDetailDesc;
    private String mPayMoney;

    private String mPayIntegral = "0",mDeductionMoney = "0";//兑换的积分数,抵扣金额

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_course_pay);
        setTitle("预约缴费", true, TITLE_TYPE_IMG, R.drawable.icon_back, false, -1, -1);
        ButterKnife.bind(this);
        getIntentData();

        initView();
        payMethodViewUtil = new PayMethodViewUtil(this,this);
        userExchange();
    }

    private void initView(){
        initStatusbar(TSATUSBAR_TYPE_BLACK_TEXT,rlTitle,R.color.gray_bar);
        ImageLoadingUtil.loadingUrl(ivCover,mPicUrl);
        tvTitle.setText(mDetailTitle);
        tvCoursePrice.setText(String.format(getString(R.string.book_course_price),mPayMoney));
        tvTotalMoney.setText(String.format(getString(R.string.book_course_price),mPayMoney));
        tvDeduction.setText(String.format(getString(R.string.course_deduction_money), mPayIntegral, mDeductionMoney));
        calculateAcrualMoney(false);
        swOpenBtn.setOn(false);
        swOpenBtn.setOnSwitchStateChangeListener(new ShSwitchView.OnSwitchStateChangeListener() {
            @Override
            public void onSwitchStateChange(boolean isOn) {
                if(isOn){//抵扣
                    calculateAcrualMoney(true);
                }else{
                    calculateAcrualMoney(false);
                }
            }
        });

        if(categoryType==1){
            tvCourseTime.setText("地点："+mDetailDesc);
            tvCourseTime.setTextColor(ContextCompat.getColor(this, R.color.color999999));
        }else{
            tvCourseTime.setText("课程时间："+mDetailDesc);
            findViewById(R.id.rl_deduction).setVisibility(View.GONE);
            findViewById(R.id.rl_pay).setVisibility(View.GONE);
        }
        btnPayMoney.setText("立即支付");
    }
    /**
     * 计算实际支付金额
     */
    private void calculateAcrualMoney(boolean isDeduction){
        mActualMoney = mPrepareMoney;
        if(isDeduction){//计算抵扣金额
            try{
                mActualMoney = mPrepareMoney-Float.parseFloat(mDeductionMoney);
            }catch (Exception e){
                mActualMoney = mPrepareMoney;
            }
        }
        tvActualMoney.setText(String.format("%.2f",mActualMoney) +"银子");
        if(Float.parseFloat(mDeductionMoney)<=0){
            tvDeduction.setText("物品金额未达到使用积分标准");
        }else{
            tvDeduction.setText(String.format(getString(R.string.course_deduction_money),mPayIntegral,mDeductionMoney));
        }
    }

    @OnClick({R.id.btnPayCourse})
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btnPayCourse:
                payMethodViewUtil.showPayMethodDialog(String.valueOf(mActualMoney));
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        payMethodViewUtil.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void paySucessResponse(int type) {
        //处理三方支付成功后的操作
        loadWaitDialog();
        String is_integarl = swOpenBtn.isOn()?"2":"1";
        HttpMethod.appointment(this,this,mCourseId,String.valueOf(type),String.valueOf(mActualMoney),is_integarl,mPayIntegral);
    }

    private void userExchange(){
        loadWaitDialog();
        HttpMethod.userExchange(this,this,String.valueOf(mPrepareMoney));
    }

    @Override
    protected void onhttpSuccess(String data, int method) {
        super.onhttpSuccess(data, method);
        if (method == HttpMethod.HTTP_CURRICULUM_APPOINTMENT) {
            CoursePayBean payBean = GsonUtil.GsonToBean(data,CoursePayBean.class);
            if(payBean!=null && !StringUtil.isEmpty(payBean.getBalance())){
                MyApplication.getInstance().sputil.put(ConstantUserInfo.USER_BALANCE,payBean.getBalance());
            }
            RxCoursePayBean payResult = new RxCoursePayBean(true);
//            RxBus.getInstance().post(payResult);
            EventBus.getDefault().post(payResult);
            myFinish();
        }else if (method == HttpMethod.HTTP_PUB_USER_EXCHANGE) {//范儿币抵扣
            ExchangeBean exchangeBean = GsonUtil.GsonToBean(data,ExchangeBean.class);
            if(exchangeBean != null){
                mPayIntegral = exchangeBean.getMax_integral();
                mDeductionMoney = exchangeBean.getMax_exchange();
                calculateAcrualMoney(false);
                tvDeduction.setText(String.format(getString(R.string.course_deduction_money), mPayIntegral, mDeductionMoney));
            }
        }
    }

    @Override
    protected void onhttpFailed(String message, int method) {
        if (method == HttpMethod.HTTP_PUB_USER_EXCHANGE) {//范儿币抵扣
            dismissWaitDialog();
        }else{
            super.onhttpFailed(message, method);
        }
    }

    private void getIntentData(){
        Intent intent = getIntent();
        mCourseId = intent.getStringExtra("id");
        categoryType = intent.getIntExtra(CATEGORYTYPE,0);
        mPicUrl = intent.getStringExtra("picUrl");
        mDetailTitle = intent.getStringExtra("detailTitle");
        mDetailDesc = intent.getStringExtra("detailDesc");
        mPayMoney = intent.getStringExtra("payMoney");
        try {
            mPrepareMoney = Float.parseFloat(mPayMoney);
        }catch (Exception e){}
    }
    /**
     *
     * @param context
     * @param categoryType
     * 判断哪里进入默认0课程，1活动
     * @param courseId
     * 对应id
     * @param picUrl
     * 封面图片url
     * @param detailTitle
     * 商品标题
     * @param detailDesc
     * 商品描述
     * @param payMoney
     * 支付总额
     */
    public static void startActivity(Activity context, int categoryType, String courseId, String picUrl, String detailTitle, String detailDesc, String payMoney){
        Intent intent = new Intent(context,CoursePayActivity.class);
        intent.putExtra("id",courseId);
        intent.putExtra("picUrl",picUrl);
        intent.putExtra("detailTitle",detailTitle);
        intent.putExtra("detailDesc",detailDesc);
        intent.putExtra("payMoney",payMoney);
        intent.putExtra(CATEGORYTYPE,categoryType);
        context.startActivityForResult(intent,REQUEST_PAY_CODE);
    }
}
